package cn.sanshuilin.kst.system.provider.write.dao;

import cn.sanshuilin.kst.common.utils.LogPrinter;
import cn.sanshuilin.kst.common.utils.Utility;
import cn.sanshuilin.kst.system.provider.bean.Location;
import org.springframework.stereotype.Repository;

import javax.persistence.Query;
import java.util.List;

/**
 * @author greenlee
 * @version v1.0
 * @create 创建时间: 2017-11-29 21:05
 * Copyright 2017  by 三水林科技有限公司
 **/
@Repository
public class LocationReq extends AbstractJpaDao<Location> {




    public long getLocationsCount(String strKeyword,double lng,double lat) {
        long count = 0;

            Query query = this.getLocationsQuery(" COUNT(*) ", strKeyword,lng,lat);
            count = Utility.toSafeLong(query.getSingleResult());

        return count;
    }

    public List<Location> getLocations(int nPageIndex, int nPageSize, String strKeyword,double lng, double lat) {

            Query query = getLocationsQuery("c", strKeyword,lng,lat);

            query.setFirstResult(nPageIndex * nPageSize);
            query.setMaxResults(nPageSize);

        return  query.getResultList();
    }


    private Query getLocationsQuery(String strChange, String strKeyword, double lng, double lat) {
        String hql = "SELECT " + strChange + " FROM Location c WHERE (c.Name LIKE :Keyword ) ";

        hql += " ORDER BY  sqrt( ( (( " + lng + "-c.Lng)*PI()*12741387*cos(((" + lat
                + "+ c.Lat)/2)*PI()/180)/180) * ((" + lng + "-c.Lng)*PI()*12741387*cos (((" + lat
                + "+c.Lat)/2)*PI()/180)/180) ) + ( ((" + lat + "-c.Lat)*PI()*12741387/180) * ((" + lat
                + "-c.Lat)*PI()*12741387/180) ) )";

        Query query = entityManager.createNativeQuery(hql,Location.class);
        query.setParameter("Keyword", "%" + strKeyword + "%");
        LogPrinter.info("----------------------"+query);
        return query;
    }
}
